<template>
  <div class="asset-container h-full">
    <NGrid :x-gap="12" :cols="4" class="h-full">
      <!-- 左侧分类树 -->
      <NGi :span="1">
        <NCard title="资产分类" :bordered="false" class="h-full rounded-8px shadow-sm">
          <template #header-extra>
            <NButton text @click="handleAddCategory">
              <template #icon>
                <icon-ic-round-plus class="text-icon" />
              </template>
            </NButton>
          </template>
          <NTree :data="categoryTree" :selectable="true" :selected-keys="selectedCategoryKeys" block-line
            @update:selected-keys="handleCategorySelect" />
        </NCard>
      </NGi>

      <!-- 右侧资产列表 -->
      <NGi :span="3">
        <NCard title="数据资产" :bordered="false" class="h-full rounded-8px shadow-sm">
          <div class="h-full flex-col">
            <!-- 查询表单 -->
            <NSpace class="pb-12px" justify="space-between">
              <NSpace>
                <NButton type="primary" @click="handleAdd">
                  <template #icon>
                    <icon-ic-round-plus class="text-icon" />
                  </template>
                  新增
                </NButton>
                <NButton type="error" :disabled="!selectedRowKeys.length" @click="handleBatchDelete">
                  <template #icon>
                    <icon-ic-round-delete class="text-icon" />
                  </template>
                  删除
                </NButton>
              </NSpace>
              <NSpace>
                <NInput v-model:value="searchKeyword" placeholder="搜索资产名称、描述、标签" clearable @keyup.enter="handleSearch">
                  <template #prefix>
                    <icon-ic-round-search class="text-icon" />
                  </template>
                </NInput>
                <NButton @click="handleRefresh">
                  <template #icon>
                    <icon-mdi-refresh class="text-icon" />
                  </template>
                  刷新
                </NButton>
                <NButton @click="showStatistics = true">
                  <template #icon>
                    <icon-mdi-chart-bar class="text-icon" />
                  </template>
                  统计
                </NButton>
              </NSpace>
            </NSpace>

            <!-- 筛选条件 -->
            <NSpace class="pb-12px">
              <NSelect v-model:value="queryParams.assetType" placeholder="资产类型" clearable :options="assetTypeOptions"
                class="w-150px" @update:value="handleQuery" />
              <NSelect v-model:value="queryParams.level" placeholder="分级标识" clearable :options="assetLevelOptions"
                class="w-150px" @update:value="handleQuery" />
              <NSelect v-model:value="queryParams.status" placeholder="状态" clearable :options="assetStatusOptions"
                class="w-150px" @update:value="handleQuery" />
            </NSpace>

            <!-- 数据表格 -->
            <NDataTable :columns="columns" :data="dataSource" :loading="loading" :pagination="pagination"
              :row-key="(row: any) => row.id" :checked-row-keys="selectedRowKeys" @update:checked-row-keys="handleCheck"
              class="flex-1-hidden" />
          </div>
        </NCard>
      </NGi>
    </NGrid>

    <!-- 新增/编辑资产对话框 -->
    <AssetOperateDrawer v-model:visible="showOperateDrawer" :operate-type="operateType" :row-data="editingData"
      :category-tree="categoryTreeRaw" @success="handleQuery" />

    <!-- 资产详情抽屉 -->
    <AssetDetailDrawer v-model:visible="showDetailDrawer" :asset-id="currentAssetId" />

    <!-- 分类管理对话框 -->
    <CategoryOperateModal v-model:visible="showCategoryModal" :operate-type="categoryOperateType"
      :row-data="editingCategory" :category-tree="categoryTreeRaw" @success="loadCategoryTree" />

    <!-- 统计信息对话框 -->
    <AssetStatisticsModal v-model:visible="showStatistics" />
  </div>
</template>

<script setup lang="ts">
import { h, onMounted, reactive, ref } from 'vue';
import type { DataTableColumns } from 'naive-ui';
import { NButton, NPopconfirm, NSpace, NTag } from 'naive-ui';
import type { AssetCategory, DataAsset, DataAssetQuery } from '@/service/api/dataplatform/asset';
import {
  AssetLevel,
  AssetStatus,
  AssetType,
  deleteDataAsset,
  getCategoryTree,
  getDataAssetList
} from '@/service/api/dataplatform/asset';
import { useLoading } from '@sa/hooks';
import AssetDetailDrawer from './modules/asset-detail-drawer.vue';
import AssetOperateDrawer from './modules/asset-operate-drawer.vue';
import AssetStatisticsModal from './modules/asset-statistics-modal.vue';
import CategoryOperateModal from './modules/category-operate-modal.vue';

const { loading, startLoading, endLoading } = useLoading(false);

// 分类树
const categoryTree = ref<any[]>([]);
const categoryTreeRaw = ref<AssetCategory[]>([]);
const selectedCategoryKeys = ref<string[]>([]);

// 查询参数
const queryParams = reactive<DataAssetQuery>({
  pageNum: 1,
  pageSize: 10
});

const searchKeyword = ref('');

// 表格数据
const dataSource = ref<DataAsset[]>([]);
const selectedRowKeys = ref<number[]>([]);

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 30, 50],
  onChange: (page: number) => {
    pagination.page = page;
    queryParams.pageNum = page;
    handleQuery();
  },
  onUpdatePageSize: (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.page = 1;
    queryParams.pageSize = pageSize;
    queryParams.pageNum = 1;
    handleQuery();
  }
});

// 对话框
const showOperateDrawer = ref(false);
const showDetailDrawer = ref(false);
const showCategoryModal = ref(false);
const showStatistics = ref(false);
const operateType = ref<'add' | 'edit'>('add');
const categoryOperateType = ref<'add' | 'edit'>('add');
const editingData = ref<DataAsset | null>(null);
const editingCategory = ref<AssetCategory | null>(null);
const currentAssetId = ref<number>(0);

// 资产类型选项
const assetTypeOptions = [
  { label: '数据表', value: AssetType.TABLE },
  { label: '视图', value: AssetType.VIEW },
  { label: 'API', value: AssetType.API },
  { label: '报表', value: AssetType.REPORT }
];

// 分级标识选项
const assetLevelOptions = [
  { label: '公开', value: AssetLevel.PUBLIC },
  { label: '内部', value: AssetLevel.INTERNAL },
  { label: '机密', value: AssetLevel.CONFIDENTIAL },
  { label: '绝密', value: AssetLevel.SECRET }
];

// 状态选项
const assetStatusOptions = [
  { label: '草稿', value: AssetStatus.DRAFT },
  { label: '已发布', value: AssetStatus.PUBLISHED },
  { label: '已归档', value: AssetStatus.ARCHIVED },
  { label: '已销毁', value: AssetStatus.DESTROYED }
];

// 表格列定义
const columns: DataTableColumns<DataAsset> = [
  { type: 'selection' },
  {
    title: '资产名称',
    key: 'name',
    width: 200,
    ellipsis: { tooltip: true },
    render: row => {
      return h(
        NButton,
        {
          text: true,
          type: 'primary',
          onClick: () => handleView(row)
        },
        { default: () => row.name }
      );
    }
  },
  {
    title: '资产类型',
    key: 'assetType',
    width: 100,
    render: row => {
      const typeMap: Record<string, { label: string; type: any }> = {
        TABLE: { label: '数据表', type: 'info' },
        VIEW: { label: '视图', type: 'success' },
        API: { label: 'API', type: 'warning' },
        REPORT: { label: '报表', type: 'error' }
      };
      const config = typeMap[row.assetType] || { label: row.assetType, type: 'default' };
      return h(NTag, { type: config.type }, { default: () => config.label });
    }
  },
  {
    title: '分类',
    key: 'categoryName',
    width: 120,
    ellipsis: { tooltip: true }
  },
  {
    title: '分级',
    key: 'level',
    width: 100,
    render: row => {
      if (!row.level) return '-';
      const levelMap: Record<string, { label: string; type: any }> = {
        PUBLIC: { label: '公开', type: 'success' },
        INTERNAL: { label: '内部', type: 'info' },
        CONFIDENTIAL: { label: '机密', type: 'warning' },
        SECRET: { label: '绝密', type: 'error' }
      };
      const config = levelMap[row.level] || { label: row.level, type: 'default' };
      return h(NTag, { type: config.type }, { default: () => config.label });
    }
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    render: row => {
      const statusMap: Record<string, { label: string; type: any }> = {
        DRAFT: { label: '草稿', type: 'default' },
        PUBLISHED: { label: '已发布', type: 'success' },
        ARCHIVED: { label: '已归档', type: 'warning' },
        DESTROYED: { label: '已销毁', type: 'error' }
      };
      const config = statusMap[row.status || 'DRAFT'] || { label: row.status, type: 'default' };
      return h(NTag, { type: config.type }, { default: () => config.label });
    }
  },
  {
    title: '使用次数',
    key: 'useCount',
    width: 100
  },
  {
    title: '描述',
    key: 'description',
    width: 200,
    ellipsis: { tooltip: true }
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 180
  },
  {
    title: '操作',
    key: 'actions',
    width: 180,
    fixed: 'right',
    render: row => {
      return h(
        NSpace,
        {},
        {
          default: () => [
            h(
              NButton,
              {
                size: 'small',
                onClick: () => handleEdit(row)
              },
              { default: () => '编辑' }
            ),
            h(
              NPopconfirm,
              {
                onPositiveClick: () => handleDelete(row.id!)
              },
              {
                default: () => '确认删除该资产吗？',
                trigger: () =>
                  h(
                    NButton,
                    {
                      size: 'small',
                      type: 'error'
                    },
                    { default: () => '删除' }
                  )
              }
            )
          ]
        }
      );
    }
  }
];

// 转换分类树数据为NTree格式
function convertCategoryTree(categories: AssetCategory[]): any[] {
  return categories.map(category => ({
    key: String(category.id),
    label: category.name,
    children: category.children ? convertCategoryTree(category.children) : undefined
  }));
}

// 加载分类树
async function loadCategoryTree() {
  try {
    const { data } = await getCategoryTree();
    categoryTreeRaw.value = data || [];
    categoryTree.value = convertCategoryTree(data || []);
  } catch {
    window.$message?.error('加载分类树失败');
  }
}

// 查询列表
async function handleQuery() {
  startLoading();
  try {
    const { data } = await getDataAssetList(queryParams);
    dataSource.value = data?.rows || [];
    pagination.itemCount = data?.total || 0;
  } catch {
    window.$message?.error('查询失败');
  } finally {
    endLoading();
  }
}

// 搜索
function handleSearch() {
  if (searchKeyword.value) {
    // 使用搜索接口
    queryParams.name = searchKeyword.value;
  } else {
    delete queryParams.name;
  }
  handleQuery();
}

// 刷新
function handleRefresh() {
  selectedRowKeys.value = [];
  handleQuery();
}

// 选择分类
function handleCategorySelect(keys: string[]) {
  selectedCategoryKeys.value = keys;
  if (keys.length > 0) {
    const categoryId = Number(keys[0]);
    if (!Number.isNaN(categoryId)) {
      queryParams.categoryId = categoryId;
    } else {
      delete queryParams.categoryId;
    }
  } else {
    delete queryParams.categoryId;
  }
  handleQuery();
}

// 新增
function handleAdd() {
  operateType.value = 'add';
  editingData.value = null;
  showOperateDrawer.value = true;
}

// 编辑
function handleEdit(row: DataAsset) {
  operateType.value = 'edit';
  editingData.value = { ...row };
  showOperateDrawer.value = true;
}

// 查看详情
function handleView(row: DataAsset) {
  currentAssetId.value = row.id!;
  showDetailDrawer.value = true;
}

// 删除
async function handleDelete(id: number) {
  try {
    await deleteDataAsset(id);
    window.$message?.success('删除成功');
    handleQuery();
  } catch {
    window.$message?.error('删除失败');
  }
}

// 批量删除
async function handleBatchDelete() {
  if (selectedRowKeys.value.length === 0) {
    window.$message?.warning('请选择要删除的数据');
    return;
  }
  try {
    await deleteDataAsset(selectedRowKeys.value);
    window.$message?.success('删除成功');
    selectedRowKeys.value = [];
    handleQuery();
  } catch {
    window.$message?.error('删除失败');
  }
}

// 选择行
function handleCheck(keys: Array<string | number>) {
  selectedRowKeys.value = keys as number[];
}

// 新增分类
function handleAddCategory() {
  categoryOperateType.value = 'add';
  editingCategory.value = null;
  showCategoryModal.value = true;
}

onMounted(() => {
  loadCategoryTree();
  handleQuery();
});
</script>

<style scoped>
.asset-container {
  padding: 16px;
}
</style>
